package com.example.app;

import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.WebResourceRoot;
import org.apache.catalina.startup.Tomcat;
import org.apache.catalina.webresources.DirResourceSet;
import org.apache.catalina.webresources.StandardRoot;

import javax.servlet.ServletException;
import java.io.File;

/**
 * localhost:9898 默认跳到 src/main/webapp/index.jsp
 */
public class SpringApplicationBoluo {

    //启动tomcat
    public static void run() {
        Tomcat tomcat = new Tomcat();
        tomcat.setPort(9898);

        String sourcePath = SpringApplicationBoluo.class.getResource("/").getPath();

        //告诉tomcat 的webapp
        try {
            //映射到index.jsp
            Context ctx = tomcat.addWebapp("/", new File("src/main/webapp").getAbsolutePath());
            WebResourceRoot resourceRoot = new StandardRoot(ctx);
            resourceRoot.addPreResources(new DirResourceSet(resourceRoot, "/WEB-INF/classes", sourcePath, "/"));
            ctx.setResources(resourceRoot);

            tomcat.start();
            tomcat.getServer().await();//异步监听
        } catch (LifecycleException | ServletException e) {

        }
    }

}
